package com.fmy.jurisdiction.config.security.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.fmy.jurisdiction.config.security.SecurityConfig;
import com.fmy.jurisdiction.core.commons.kits.MybatisPlusKit;
import com.fmy.jurisdiction.core.unusual.BizAuthenticationException;
import com.fmy.jurisdiction.modular.mapper.AdminRolePermMapper;
import com.fmy.jurisdiction.modular.model.AdminUser;
import com.fmy.jurisdiction.modular.service.IAdminUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName UserDetailsServiceImpl
 * @Description TODO
 * @createTime 2019/9/16 17:35
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IAdminUserService userService;

    @Autowired
    private AdminRolePermMapper rolePermMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AdminUser user = userService.getOne(MybatisPlusKit.<AdminUser>q()
                .eq(AdminUser.DEL_FLAG,false)
                .and(i->i.eq(AdminUser.USER_LOGIN, s).or().eq(AdminUser.USER_PHONE, s)));
        if (user == null) {
            throw new UsernameNotFoundException("未找到该用户");
        }
        SecurityConfig.THREADLOCAL_SALT.set(user.getSalt());
        UserDetailsEntity userDetailsEntity = new UserDetailsEntity();
        BeanUtils.copyProperties(user, userDetailsEntity);
        if (StrUtil.isEmpty(userDetailsEntity.getRoles())) throw new BizAuthenticationException("请联系管理员为您分配角色");
        //获取权限
        userDetailsEntity.setPermissions(rolePermMapper
                .findByRoleIdToPermCode(Convert.toList(Integer.class, userDetailsEntity.getRoles())));
        return userDetailsEntity;
    }
}
